package com.zzw.service.Impl;

import com.zzw.bean.Menu;
import com.zzw.bean.Roles;
import com.zzw.dao.MenuMapper;
import com.zzw.dao.RolesMapper;
import com.zzw.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 赵志伟
 * @version 1.0
 */
@SuppressWarnings({"all"})
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    
    @Autowired
    private RolesMapper rolesMapper;
    
    // 超级管理员角色名称
    private static final String SUPER_ADMIN_ROLE = "超级管理员";

    @Override
    public List<Menu> selectMenuRootElement() {
        List<Menu> menus = menuMapper.selectMenuRootElement();
        return menus;
    }

    @Override
    public List<Menu> selectMenuChildElement(Menu menu) {
        List<Menu> menus = menuMapper.selectMenuChildElement(menu);
        return menus;
    }

    @Override
    public List<Menu> selectMenuNode(Menu menu) {
        List<Menu> menus = menuMapper.selectMenuNode(menu);
        return menus;
    }

    @Override
    public List<Menu> selectMenuNodeByUserId(Menu menu, Integer userId) {
        // 检查用户是否为超级管理员
        boolean isSuperAdmin = false;
        List<Roles> userRoles = rolesMapper.selectRolesByUserId(userId);
        for (Roles role : userRoles) {
            if (SUPER_ADMIN_ROLE.equals(role.getName())) {
                isSuperAdmin = true;
                break;
            }
        }
        
        // 如果是超级管理员，返回所有菜单
        if (isSuperAdmin) {
            // 这里使用selectMenuNode查询所有菜单，不进行权限过滤
            return menuMapper.selectMenuNode(menu);
        }
        
        // 如果不是超级管理员，则按权限返回菜单
        List<Menu> menus = menuMapper.selectMenuNodeByUserId(menu, userId);
        return menus;
    }

    @Override
    public List<Menu> selectMenuNodeByRoleId(Menu menu, Integer roleId) {
        List<Menu> menus = menuMapper.selectMenuNodeByRoleId(menu, roleId);
        return menus;
    }

    @Override
    public boolean insertNode(Menu menu) {
        return menuMapper.insertSelective(menu) >= 1 ? true : false;
    }

    @Override
    public boolean deleteNode(Integer id) {
        return menuMapper.deleteByPrimaryKey(id) >= 1 ? true : false;
    }

    @Override
    public boolean updateNode(Menu menu) {
        return menuMapper.updateByPrimaryKeySelective(menu) >= 1 ? true : false;
    }
}
